package com.wdb.modules.system.rest;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.wdb.modules.system.domain.Job;
import com.wdb.modules.system.domain.dto.JobUploadDTO;
import com.wdb.modules.system.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/3/25 0025 16:23
 */
@Slf4j
@Component
public class JobEasyExcelDataListener implements ReadListener<JobUploadDTO> {
  /** 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收 */
  private static final int BATCH_COUNT = 2;

  private JobService jobService;
  /** 缓存的数据 */
  private List<Job> cachedDataList = new ArrayList<>(BATCH_COUNT);

  public JobEasyExcelDataListener(JobService jobService) {
    this.jobService = jobService;
  }

  @Override
  public void onException(Exception e, AnalysisContext analysisContext) throws Exception {
    log.info("onException--{}", e);
  }

  @Override
  public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {
    log.info("invokeHead--{}", map);
  }

  @Override
  public void invoke(JobUploadDTO jobUploadDTO, AnalysisContext analysisContext) {

    log.info("解析到一条数据:{}", JSON.toJSONString(jobUploadDTO));
    Job job = new Job();
    job.setEnabled("启用".equals(jobUploadDTO.getEnabled()));
    job.setName(jobUploadDTO.getName());
    job.setJobSort(jobUploadDTO.getJobSort());
    cachedDataList.add(job);
    if (cachedDataList.size() > BATCH_COUNT) {
      //
      jobService.saveBatch(cachedDataList);
      cachedDataList.clear();
    }
  }

  @Override
  public void extra(CellExtra cellExtra, AnalysisContext analysisContext) {
    log.info("extra---");
  }

  @Override
  public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    log.info("所有数据解析完成！");
  }

  @Override
  public boolean hasNext(AnalysisContext analysisContext) {
    return true;
  }
}
